import {defineStore} from 'pinia'
import {router} from "/@/router";
import {store as storeName} from "/@/store";
import store from 'store'
import {login, logout, selectLoginUserInfo} from "/@/api/auth/login";
import {MenuModel} from "/@/api/system/model/MenuModel";
import {listMenuTreeByLoginUser} from "/@/api/system/menuApi";
import {loadRouter, setCurrentTab} from "/@/utils/router/router-util";
import {RouteLocationNormalized} from "vue-router";
import {useMenuStoreHook} from "/@/store/modules/menu";
import {UserPostModel} from "/@/api/system/model/UserModel";
import {ElMessage} from "element-plus";

const menuStore = useMenuStoreHook()
export const useUserStore: any = defineStore({
    id: 'user',
    state: () => {
        let homePage = store.get("homePage")
        return {
            realName: '' as string,
            userId: '',
            orgId: '',
            comId: '',
            avatar: '',
            homePage: homePage,
            menu: [] as MenuModel[],
            menuLoad: false,
            posts: [] as UserPostModel[],
            roles: [] as string[],
            auths: [] as string[]
        }
    },
    getters: {},
    actions: {
        async login(param: object, callBack: Function) {
            try {
                let res = await login(param)
                store.set("token", res.token)
                await this.getUserInfo()
                router.push({
                    name: this.homePage
                })
                let routes = router.getRoutes()
                let routeRecordNormalized = routes.find(res => res.name === this.homePage) as any;
                if (routeRecordNormalized) {
                    setCurrentTab(router, routeRecordNormalized);
                }
                ElMessage.success("登录成功")
                callBack()
            } catch (e) {
                callBack()
            }
        },
        async logout() {
            await logout()
            menuStore.clear()
            this.menu = []
            store.set('token', '')
        },
        async getUserInfo() {

            let res = await selectLoginUserInfo(false)
            this.realName = res.realName
            this.userId = res.userId
            this.orgId = res.orgId
            this.comId = res.comId
            this.avatar = res.avatar
            this.menuLoad = true
            this.homePage = res.homePage
            this.auths = res.auths
            this.roles = res.roles
            this.posts = res.posts
            store.set("homePage", this.homePage)
            await this.getRouter();
        },
        async getRouter() {
            let res = await listMenuTreeByLoginUser(false) as MenuModel[]
            this.menu = res
            if(!this.menu || this.menu.length == 0){
                ElMessage.error("当前用户没有菜单权限")
                throw new Error("当前用户没有菜单权限")
            }
            if(!this.checkHomePage(this.menu)){
                ElMessage.error("当前用户没有主页菜单权限")
                throw new Error("当前用户没有主页菜单权限")
            }

            loadRouter(res, "index", router, [])
        },
        setMenu(menu: MenuModel[]) {
            this.menu = menu
        },
        setMenuLoad(menuLoad: boolean) {
            this.menuLoad = menuLoad
        },
        checkHomePage(menus: MenuModel[]){
            if(menus && menus.length > 0){
                for (const menu of menus) {
                    if(menu.name == this.homePage){
                        return true;
                    }else if(menu.children && menu.children.length > 0){
                       let check = this.checkHomePage(menu.children)
                        if(check){
                            return check;
                        }
                    }

                }
            }
            return false;
        }

    }
})

export function useUserStoreHook() {
    return useUserStore(storeName);
}

